package com.nirvana.resolve;

import com.nirvana.config.PluginConfig;
import com.nirvana.convert.CamelCaseConverter;
import com.nirvana.data.DefPropertyData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;

public class XmlResolver extends AbstractResolver {
    public XmlResolver(File file) {
        super(file);
    }

    @Override
    public List<DefPropertyData> resolve() {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(file);
            Element rootElement = document.getRootElement();
            Element element = rootElement.element(getElement());
            return element.attributes().stream().filter(attr -> !PluginConfig.getInstance().checkIgnoreField(attr.getName())).map(attr -> {
                DefPropertyData data = new DefPropertyData();
                String sourceName = attr.getName();
                data.setPropertyName(CamelCaseConverter.toCamelCase(sourceName, true));
                data.setSourceName(sourceName);
                data.setComment(attr.getValue());
                data.setTypeIndex("String");
                return data;
            }).toList();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getDefClassName() {
        String fileName = getElement();
        return CamelCaseConverter.toCamelCase(fileName, false) + "Def";
    }

    @NotNull
    private String getElement() {
        String name = file.getName();
        return name.substring(0, name.lastIndexOf("."));
    }
}
